﻿using System.Linq;
using OpenLS.Spreadsheet.Formats.JsonStructures;
using Raven.Client;
using Raven.Client.Document;

namespace QuantumWorkspace.SessionManager
{
    public class BigDataTableDAL
    {
        private IDocumentStore dbStore;

        public BigDataTableDAL()
        {
            dbStore = new DocumentStore
                {
                    Url = "http://ravenDB.dataprovider.com",
                    DefaultDatabase = "QuantumWorkspacesBigDataTable"
                };
            Initialize();
        }

        public void Initialize()
        {
            dbStore.Initialize();
            dbStore.Conventions.RegisterIdConvention<JsonTableDocument>(
                (dbname, dbCommand, jsonTableDocument) =>
                "tables/" + jsonTableDocument.CurrentTable.Name + "/" + jsonTableDocument.CurrentTable.IsPublic);
        }

        public JsonTableDocument GetOrCreate(JsonTableDocument tableDocument)
        {
            using (var session = dbStore.OpenSession())
            {
                var existingTable = GetTableDocument(tableDocument.CurrentTable.Name);
                if (existingTable == null)
                {
                    session.Store(tableDocument);
                    session.SaveChanges();
                    return tableDocument;
                }
                else
                {
                    return existingTable;
                }
            }
        }


        public JsonTableDocument GetTableDocument(string strTableName)
        {
            // Create a new session, retrieve an entity, and change it a bit
            using (var session = dbStore.OpenSession())
            {
                JsonTableDocument currentDoc = session.Query<JsonTableDocument>()
                    .Where(x => x.CurrentTable.Name == strTableName)
                    .FirstOrDefault();

                return currentDoc;
            }

        }

    }
}
